import { Button, Modal, List, Space, Input, Row, Col, Popconfirm, message } from 'antd'
import { useEffect, useState, useImperativeHandle } from 'react'

import { http } from '@/utils'
import { useStore } from '@/store'
import './index.scss'
import {
  directionTypeOpt,
  stockSupportTypeOpt
} from './const'
const Ordermodalopen = (props) => {
  const configModalOpenOk = () => {
    props.changeConfigModal('child msg')
    setConfigModalOpen(false)
    setLoading(false)
    setOrderUserList([])

  }
  const configModalOpenCancel = () => {
    props.changeConfigModal('child msg')
    setConfigModalOpen(false)
    setLoading(false)
    setOrderUserList([])
  }
  const closeModalOpen = () => {
    setLoading(false)
    setConfigModalOpen(false)
    setOrderUserList([])
    props.changeConfigModal('child msg')
  }
  const [configModalOpen, setConfigModalOpen] = useState(false)
  const [configRow, setConfigRow] = useState({})
  const [loading, setLoading] = useState(false)
  const [orderUserList, setOrderUserList] = useState([])
  const [featureTypeOpt, setFeatureTypeOpt] = useState([])


  const { loginStore } = useStore()
  // 父组件调用打开模态框
  useImperativeHandle(props.onRef, () => {
    return {
      openConfigModalOpen: openConfigModalOpen,
    }
  })
  const openConfigModalOpen = (data) => {
    console.log('品种', {
      ...data,
      // featureName: '液化石油气2305	',
      // featureCode: 'PG2305.DCE',
    })
    setConfigRow({
      ...data,
      // // featureName: '液化石油气2305	',
      // featureCode: 'PG2305.DCE',
    })
    setConfigModalOpen(true)
  }
  const partOnChange = (e, row) => {
    let value = e.target.value.replace(/^(0+)|[^\d]+/g, '')
    value = +value > +row.maxSize ? row.maxSize : value
    const list = orderUserList.map(item => {
      return {
        ...item,
        orderPart: item._id === row._id ? value : item.orderPart
      }
    })
    setOrderUserList(list)
  }
  // 多单下单份数校验
  const partMoreOnChange = (e, row) => {
    let value = e.target.value.replace(/^(0+)|[^\d]+/g, '')
    value = +value > +row.maxSize ? row.maxSize : value
    // value = value > row.partMore ? row.partMore : value
    const list = orderUserList.map(item => {
      return {
        ...item,
        orderMore: item._id === row._id ? value : item.orderMore
      }
    })
    // console.log(list)
    setOrderUserList(list)
  }
  const partEmptyOnChange = (e, row) => {
    let value = e.target.value.replace(/^(0+)|[^\d]+/g, '')
    value = +value > +row.maxSize ? row.maxSize : value
    const list = orderUserList.map(item => {
      return {
        ...item,
        orderEmpty: item._id === row._id ? value : item.orderEmpty
      }
    })
    // console.log(list)
    setOrderUserList(list)
  }

  // 交易下单
  const orderSubmit = (row, orderType) => {
    const data = {
      ...configRow,
      stockSupportType: row.stockSupportType,
      supportEmpty: row.supportEmpty,
      username: row.account,
      password: row.password,
      featureCode: configRow.featureCode,
      amount: row.orderPart,
      directionType: null,
      offSetType: null,
      orderPrice: null,  // 开发中 不传
      categoryType: row.categoryType,
      priceType: row.stockSupportType === 1 || row.stockSupportType === 2 ? 52 : 53, // 49 市价 53 对手价
      // tbUserAlarmInfoId: configRow.id,
      isCredit: false,
      featureType: configRow.featureType,
      varietyCode: configRow.featureCode,
      userId: loginStore.userId,
    }
    const arrData = []
    switch (orderType) {
      case 1: // 股票买入
        arrData.push({
          ...data,
          directionType: 48, // 交易方向 48 多 49 空
          offSetType: 48,
        })
        break
      case 2: // 股票卖出
        arrData.push({
          ...data,
          directionType: 49, // 交易方向 48 多 49 空
          offSetType: 49,
        })
        break
      case 3: // 股票融资买入
        arrData.push({
          ...data,
          directionType: 48, // 交易方向 48 多 49 空
          offSetType: 48,
          isCredit: true
        })
        break
      case 4: // 股票融资卖出
        arrData.push({
          ...data,
          directionType: 49, // 交易方向 48 多 49 空
          offSetType: 49,
          isCredit: true
        })
        break
      case 5: // 期货  开多
        arrData.push({
          ...data,
          directionType: 48, // 交易方向 48 多 49 空
          offSetType: 48,
          amount: row.orderMore
        })
        break
      case 6: // 期货  平多
        arrData.push({
          ...data,
          directionType: 49, // 交易方向 48 多 49 空
          offSetType: 49,
          amount: row.orderMore
        })
        break
      case 7: // 期货  反空
        arrData.push({
          ...data,
          directionType: 49,
          offSetType: 49,
          amount: row.orderMore
        })
        arrData.push({
          ...data,
          directionType: 49,
          offSetType: 48,
          amount: row.orderMore
        })
        break
      case 8: // 期货  开空
        arrData.push({
          ...data,
          directionType: 49, // 交易方向 48 多 49 空
          offSetType: 48,
          amount: row.orderEmpty
        })
        break
      case 9: // 期货  平空
        arrData.push({
          ...data,
          directionType: 48, // 交易方向 48 多 49 空
          offSetType: 49,
          amount: row.orderEmpty
        })
        break
      case 10: // 期货  反多
        arrData.push({
          ...data,
          directionType: 48, // 交易方向 48 多 49 空
          offSetType: 49,
          amount: row.orderEmpty
        })
        arrData.push({
          ...data,
          directionType: 48, // 交易方向 48 多 49 空
          offSetType: 48,
          amount: row.orderEmpty
        })
        break
      default:
        return
    }
    console.log(arrData)
    http.post('/alarm/deliversign/order', arrData).then((res) => {
      message.success(res.body)
      setConfigModalOpen(false)
      setOrderUserList([])
    })

  }
  useEffect(() => {
    // 获取用户持仓
    const getPosition = async () => {
      const res = await http.post('/alarm/deliversign/position', {
        userId: loginStore.userId,
        featureCode: configRow.featureCode
      })
      const list = []
      for (const key in res.body) {
        const element = res.body[key]
        const row = {
          _id: key,
          part: 0,// 股票  持仓份数
          partMore: 0,// 期货 多单 持仓份数
          partEmpty: 0,// 期货 空单 持仓份数
          orderPart: 1,// 股票  下单份数
          orderMore: 1, // 期货 买多 下单份数
          orderEmpty: 1, // 期货 卖空 下单份数
        }
        element.map((item, i) => {
          const supportEmptyRow = directionTypeOpt.filter(citem => +citem.dictCode === item.tbTradeUserInfo.supportEmpty)[0]
          const stockSupportTypeRow = stockSupportTypeOpt.filter(citem => +citem.dictCode === item.loginResponseData.stockSupportType)[0]
          row.account = item.tbTradeUserInfo.account  // 账号名称
          row.password = item.tbTradeUserInfo.password  // 账号密码
          row.categoryType = item.loginResponseData.categoryType  // 市场类型
          // 期货 开多 股票 买多
          if (item.directionType === 48) {
            row.part = item.part
            row.partMore = item.part
          } else {
            row.partEmpty = item.part
          }
          row.maxSize = item.tbTradeUserInfo.maxSize  // 最大下单份数
          row.supportEmpty = item.tbTradeUserInfo.supportEmpty  // 账号类型 supportEmpty  1 期货账号 0 股票账号
          row.supportEmptyName = supportEmptyRow ? supportEmptyRow.dictName : '-' // 自定义
          row.stockSupportType = item.loginResponseData.stockSupportType  // 股票账号类型 stockSupportType  0 null 1 沪港通 2 深港通 3 沪港通+深港通 4 融资融卷
          row.stockSupportTypeName = stockSupportTypeRow ? stockSupportTypeRow.dictName : '-'  // 自定义
          return item
        })
        list.push(row)
      }
      // 过滤品种可交易类型账号 featureType  2 ETF 3 A股 4期货 5 港股 6 外盘
      const listFilter = list.filter(item => {
        // 期货 
        if (configRow.featureType === 4) {
          // 期货只返回期货账号
          return item.supportEmpty === 1
        } else {
          let hasItem = false
          switch (configRow.featureType) {
            // ETF
            case 2:
              // 是否支持融资买入 
              // if (configRow.marginTrading) {
              hasItem = item.supportEmpty === 0 && (item.stockSupportType === 4 || item.stockSupportType === 0)
              // } else {
              //   hasItem = item.supportEmpty === 0 && item.stockSupportType === 0
              // }
              break
            // A股
            case 3:
              // 是否支持融资买入 
              // if (configRow.marginTrading) {
              hasItem = item.supportEmpty === 0 && (item.stockSupportType === 4 || item.stockSupportType === 0)
              // } else {
              //   hasItem = item.supportEmpty === 0 && item.stockSupportType === 0
              // }
              break
            // 港股
            case 5:
              // 是否支持融资买入 
              if (configRow.marginTrading) {
                hasItem = item.supportEmpty === 0 &&
                  (item.stockSupportType === 1 || item.stockSupportType === 2 || item.stockSupportType === 3 || item.stockSupportType === 4)
              } else {
                hasItem = item.supportEmpty === 0 &&
                  (item.stockSupportType === 1 || item.stockSupportType === 2 || item.stockSupportType === 3)
              }
              break
            default:
              break
          }
          return hasItem
        }
      })
      console.log('用户持仓', listFilter)
      setOrderUserList(listFilter)
    }
    const getDicfig = async () => {
      const res = await http.post('/alarm/deliversign/getDicConfig', {
        userId: loginStore.userId,
        dictIds: [1000, 1001, 1002, 1003, 1004, 1005, 1006]
      })
      setFeatureTypeOpt(res.body['1001'].map(item => ({ label: item.dictName, value: item.dictCode })))
      console.log('字典-', res.body)
    }
    if (!featureTypeOpt.length) {
      getDicfig()
    }
    if (configRow.featureCode && configModalOpen) {
      getPosition()
    }
    if (props.configModalData.configModalOpen) {
      setConfigModalOpen(props.configModalData.configModalOpen)
      setConfigRow(props.configModalData.configModalRow)
    }

  }, [configModalOpen, configRow, loginStore, featureTypeOpt, props.configModalData])
  return (
    <>
      <Modal
        className='orderModal'
        title={`${configRow.featureName} ${configRow.featureCode} ${configRow.freqName}`}
        open={configModalOpen}
        onOk={configModalOpenOk}
        onCancel={configModalOpenCancel}
        width={650}
        footer={[
          <Button key="submit" type="primary" loading={loading} onClick={closeModalOpen}>
            关闭
          </Button>
        ]}
      >
        <List
          bordered
          className='orderList'
          size='small'
          header={
            <Row>
              <Col span={8}>子账号名称</Col>
              <Col span={16}>
                <Row>
                  <Col span={12}>持仓份数</Col>
                  <Col span={12}>下单份数</Col>
                  {/* <Col span={12}>操作</Col> */}
                </Row>
              </Col>

            </Row>
          }
          dataSource={orderUserList}
          renderItem={(citem, index) => {
            return <List.Item key={citem._id} >
              {citem.supportEmpty === 1 ? <Row style={{ width: '100%' }}>
                <Col span={8}>
                  <span>{citem.account}</span>
                </Col>
                <Col span={16}>
                  {/* 多单 */}
                  <Row>
                    <Col span={12}>
                      <span>多单：</span>
                      <span>{citem.partMore || 0} </span>
                      <span>份</span>
                    </Col>
                    <Col span={12}>
                      <Input
                        size='small'
                        value={citem.orderMore}
                        placeholder="请输入"
                        style={{ width: 80 }}
                        onChange={(e) => partMoreOnChange(e, citem)}
                      />
                    </Col>
                  </Row>
                  <Row style={{ marginTop: 10 }}>
                    <Col span={24}>
                      <Space >
                        <Popconfirm
                          title={<div>
                            <p>确认要发出委托？</p>
                            <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，开多 ${citem.orderMore} 份`}</p>
                          </div>}
                          onConfirm={() => orderSubmit(citem, 5)}
                          disabled={!citem.orderMore}
                        >
                          <Button size="small" disabled={!citem.orderMore}>开多</Button>
                        </Popconfirm>
                        <Popconfirm
                          title={<div>
                            <p>确认要发出委托？</p>
                            <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，开多 ${citem.orderMore} 份`}</p>
                          </div>}
                          onConfirm={() => orderSubmit(citem, 6)}
                          disabled={!citem.orderMore}
                        >
                          <Button size="small" disabled={!citem.orderMore || !citem.partMore} > 平多</Button >
                        </Popconfirm>
                        <Popconfirm
                          title={<div>
                            <p>确认要发出委托？</p>
                            <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，反空 ${citem.orderMore} 份`}</p>
                          </div>}
                          onConfirm={() => orderSubmit(citem, 7)}
                          disabled={!citem.orderMore}
                        >
                          <Button size="small" disabled={!citem.orderMore || !citem.partMore} > 反空</Button >
                        </Popconfirm>
                      </Space>
                    </Col>
                  </Row>
                  {/* 空单 */}
                  <Row style={{ marginTop: 15 }}>
                    <Col span={12}>
                      <span>空单：</span>
                      <span>{citem.partEmpty || 0} </span>
                      <span>份</span>
                    </Col>
                    <Col span={12}>
                      <Input
                        size='small'
                        placeholder="请输入"
                        style={{ width: 80 }}
                        value={citem.orderEmpty}
                        onChange={(e) => partEmptyOnChange(e, citem)}
                      />
                    </Col>
                  </Row>
                  <Row style={{ marginTop: 10 }}>
                    <Col span={24}>
                      <Space >
                        <Popconfirm
                          title={<div>
                            <p>确认要发出委托？</p>
                            <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，开空 ${citem.orderEmpty} 份`}</p>
                          </div>}
                          onConfirm={() => orderSubmit(citem, 8)}
                          disabled={!citem.orderEmpty}
                        >
                          <Button size="small" disabled={!citem.orderEmpty}>开空</Button>
                        </Popconfirm>
                        <Popconfirm
                          title={<div>
                            <p>确认要发出委托？</p>
                            <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，开空 ${citem.orderEmpty} 份`}</p>
                          </div>}
                          onConfirm={() => orderSubmit(citem, 9)}
                          disabled={!citem.orderEmpty || !citem.partEmpty}
                        >
                          <Button size="small" disabled={!citem.orderEmpty || !citem.partEmpty}> 平空</Button >
                        </Popconfirm>
                        <Popconfirm
                          title={<div>
                            <p>确认要发出委托？</p>
                            <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，反多 ${citem.orderEmpty} 份`}</p>
                          </div>}
                          onConfirm={() => orderSubmit(citem, 10)}
                          disabled={!citem.orderEmpty || !citem.partEmpty}
                        >
                          <Button size="small" disabled={!citem.orderEmpty || !citem.partEmpty}> 反多</Button >
                        </Popconfirm>
                      </Space>
                    </Col>
                  </Row>
                </Col>
              </Row> : <Row style={{ width: '100%' }}>
                {/* 股票 */}
                <Col span={8}>
                  <span>{citem.account}</span>
                </Col>
                <Col span={16}>
                  <Row >
                    <Col span={12}>
                      <span>{citem.part || 0} </span>
                      <span>份</span>
                    </Col>
                    <Col span={12}>
                      <Input
                        size='small'
                        value={citem.orderPart}
                        placeholder="请输入"
                        style={{ width: 80 }}
                        onChange={(e) => partOnChange(e, citem)}
                      />
                    </Col>
                  </Row>
                  <Row style={{ marginTop: 10 }}>
                    <Col span={24}>
                      <Space >
                        <Popconfirm
                          title={<div>
                            <p>确认要发出委托？</p>
                            <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，买 ${citem.orderPart} 份`}</p>
                          </div>}
                          onConfirm={() => orderSubmit(citem, 1)}
                          disabled={!citem.orderPart}
                        >
                          <Button size="small" disabled={!citem.orderPart}>买</Button>
                        </Popconfirm>
                        <Popconfirm
                          title={<div>
                            <p>确认要发出委托？</p>
                            <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，卖 ${citem.orderPart} 份`}</p>
                          </div>}
                          onConfirm={() => orderSubmit(citem, 2)}
                          disabled={!citem.part || !citem.orderPart}
                        >
                          <Button size="small" disabled={!citem.part || !citem.orderPart}> 卖</Button >
                        </Popconfirm>
                        {/* 股票账户是否是融资买入 */}
                        {(citem.stockSupportType === 4 && configRow.marginTrading) ? <Space >
                          <Popconfirm
                            title={<div>
                              <p>确认要发出委托？</p>
                              <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，融资买入 ${citem.orderPart} 份`}</p>
                            </div>}
                            onConfirm={() => orderSubmit(citem, 3)}
                            disabled={!citem.orderPart}
                          >
                            <Button size="small" disabled={!citem.orderPart}>融资买入</Button>
                          </Popconfirm>
                          <Popconfirm
                            title={<div>
                              <p>确认要发出委托？</p>
                              <p style={{ margin: 0 }}>{`${citem.account}，对手价+一跳，卖卷还款 ${citem.orderPart} 份`}</p>
                            </div>}
                            onConfirm={() => orderSubmit(citem, 4)}
                            disabled={!citem.part || !citem.orderPart}
                          >
                            <Button size="small" disabled={!citem.part || !citem.orderPart}>卖卷还款</Button>
                          </Popconfirm>
                        </Space> : ''}
                      </Space>
                    </Col>
                  </Row>
                </Col>
              </Row>}
            </List.Item>
          }}
        />
      </Modal >
    </>
  )
}
export default Ordermodalopen
